<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI

class Home_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('result_model', '', 'TRUE');
        $this->load->model('user', '', true);

        if (!$this->session->userdata('logged_in')) {
            redirect('login', 'refresh');
        }

        $this->load->library('authentication');
        $this->load->helper('t');
        $this->loggedUser = $this->authentication->getLoggedUser();
        $this->authentication->redirectIfNotBe(array('HR', 'SC'));
    }

    function index() {
        // load danh sách rsm/kam
        $this->load->model('region');
        $regions = $this->region->get_list();
        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;
        $rsmList = $this->user->get_list_by_title(array('RSM', 'KAM'));
        $viewData['rsmList'] = $rsmList;

        // load todo list
        $this->load->model('evaluation');
        $e = $this->evaluation->get_last();

        $this->load->model('todo');
        $todoList = $this->todo->get_list_by_evaluation($e['id']);
        foreach ($todoList as &$each) {
            if (time() < strtotime($each['start_day'])) {
                $each['status'] = 'coming';
            } else if (time() <= strtotime($each['end_day'])) {
                $each['status'] = 'current';
            } else {
                $each['status'] = 'done';
            }
        }
        $viewData['todoList'] = $todoList;

        $this->load->view(get_folder($this->loggedUser->title) . '/home_view', $viewData);
    }

    function settings() {
        $this->load->model('Settings');
        $settings = $this->Settings->get(1);

        if ($this->input->post('Command') == 'Submit') {
            $new = array(
                'id' => 1,
                'att_high_score' => $this->input->post('att_high_score'),
                'att_medium_score' => $this->input->post('att_medium_score'),
                'ex' => $this->input->post('ex'),
                'he' => $this->input->post('he'),
                'ef' => $this->input->post('ef'),
                'be' => $this->input->post('be'),
                'ni' => $this->input->post('ni'),
                'sale_ratio' => $this->input->post('sale_ratio'),
                'test_ratio' => $this->input->post('test_ratio'),
                'from_email' => $this->input->post('from_email'),
                'from_name' => $this->input->post('from_name'),
                'smtp_sec' => $this->input->post('smtp_sec'),
                'smtp_host' => $this->input->post('smtp_host'),
                'smtp_port' => $this->input->post('smtp_port'),
                'smtp_username' => $this->input->post('smtp_username'),
                'smtp_password' => $this->input->post('smtp_password'),
                    //'google_app_pass' => $this->input->post('google_app_password')
            );
            $message = $this->Settings->update($new);

            $settings = $this->Settings->get(1);
        }

        $viewData['settings'] = $settings;
        $viewData['message'] = $message;


        $this->load->view(get_folder($this->loggedUser->title) . '/settings', $viewData);
    }

    function export() {

        $this->load->model('evaluation');
        $this->load->model('calibration');
        $evaluation = $this->evaluation->get_last();

        $fields = array(
            'region' => 'Region',
            'location' => 'Location',
            'code' => 'Code',
            'title' => 'Title',
            'fullname' => 'Full name',
            'teamleader_code' => 'Team leader code',
            'teamleader_name' => 'Team leader name',
            'ss_code' => 'Supervisor code',
            'ss_name' => 'Supervisor name',
            'rsm_code' => 'RSM code',
            'rsm_name' => 'RSM name',
            'start_date' => 'Date started',
            'end_date' => 'Date ended',
            'status' => 'Status',
            'status2' => 'Status2',
            'sale_performance' => 'Sale performance',
            'test_result' => 'Kết quả trắc nhgiệm',
            'first_rating' => 'First rating',
            'att_result' => 'Kết quả thái độ',
            'final_rating' => 'Final rating',
            'calibration' => 'Kết quả Calibration'
        );

        $this->load->model('region');
        $regions = $this->region->get_list();
        $regionDic = array();
        foreach ($regions as $key => $value) {
            $regionDic[$value['rsm_code']] = $value['region_name'];
        }
        $viewData['regionDic'] = $regionDic;

        $users = $this->user->get_list_by_title(get_employee_titles());
        get_final_results($users, $evaluation['id']);


        if ($this->input->post('Command') == 'Submit') {
            $toExport = array();
            foreach ($users as $user) {
                $row = array();

                $selectedFields = $this->input->post('fields');
                if ($selectedFields == false) {
                    return;
                }

                foreach ($selectedFields as $value) {
                    switch ($value) {
                        case 'region':
                            $row['Region'] = $regionDic[$user['rsm_code']];
                            break;
                        case 'location':
                            $row['Location'] = $user['location'];
                            break;
                        case 'code':
                            $row['Code'] = $user['code'];
                            break;
                        case 'title':
                            $row['Title'] = $user['title'];
                            break;
                        case 'fullname':
                            $row['Full name'] = $user['name'];
                            break;
                        case 'teamleader_code':$row['Team leader code'] = $user['teamleader_code'];
                            break;
                        case 'teamleader_name':
                            $tl = $this->user->get_user_by_code($user['teamleader_code']);
                            $row['Team leader name'] = $tl != false ? $tl['name'] : '';
                            break;
                        case 'ss_code':
                            $row['SS code'] = $user['supervisor_code'];
                            break;
                        case 'ss_name':
                            $ss = $this->user->get_user_by_code($user['supervisor_code']);
                            $row['SS name'] = $ss != false ? $ss['name'] : '';
                            break;
                        case 'rsm_code':$row['RSM code'] = $user['rsm_code'];
                            break;
                        case 'rsm_name':
                            $rsm = $this->user->get_user_by_code($user['rsm_code']);
                            $row['RSM name'] = $rsm != false ? $rsm['name'] : '';
                            break;
                        case 'start_date':$row['Date started'] = $user['starting_day'];
                            break;
                        case 'end_date':$row['Date ended'] = $user['stoppping_day'];
                            break;
                        case 'status':$row['Status'] = $user['status'];
                            break;
                        case 'status2':$row['Status2'] = $user['status2'];
                            break;
                        case 'sale_performance':$row['Sale performance'] = $user['saleResult'] != false ? number_format($user['saleResult']['score'], 2, '.', '') . '%' : '';
                            break;
                        case 'test_result':$row['Kết quả trắc nghiệm'] = $user['testResult'] != false ? number_format($user['testResult']['percentage'], 2, '.', '') . '%' : '';
                            break;
                        case 'first_rating':$row['First rating'] = $user['firstRating'] != false ? $user['firstRating']['name'] : '';
                            break;
                        case 'att_result':$row['Kết quả thái độ'] = $user['attResult'] != false ? $user['attResult']['rating'] : '';
                            break;
                        case 'final_rating':$row['Final rating'] = $user['finalRating'] != false ? $user['finalRating']['name'] : '';
                            break;
                        case 'calibration':
                            $caliResult = $this->calibration->get_by_code_and_eid($user['code'], $evaluation['id']);
                            $row['Kết quả Calibration'] = $caliResult != false ? $caliResult['final_result'] : '';
                            break;
                    }
                }
                $toExport[] = $row;
            }

            $str = ConvertToCSV($toExport);
            $CSVString = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $str);
            header("Content-type: text/csv");
            header("Content-Disposition: attachment; filename=danh_gia.csv");
            //header('Content-length: ' . strlen($CSVString));
            header("Expires: 0");
            //header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Pragma: no-cache"); //header("Pragma: public");


            echo $CSVString;
            return;
        }
        
        $viewData['fields'] = $fields;

        $this->load->view(get_folder($this->loggedUser->title) . '/export_csv', $viewData);
    }

    function logout() {
        $this->load->helper('cookie');
        $this->session->unset_userdata('logged_in');
        $institute_id = $this->session->userdata('institute_id');
        $this->session->sess_destroy();
        session_destroy();
        delete_cookie("rid");
        redirect('login/index/' . urlencode(base64_encode($institute_id)), 'refresh');
    }

}
?>


